package com.aisb.manage;

import com.aisb.core.InitParam;
import com.aisb.core.SessionBean;
import com.aisb.core.util.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class AuthService {
    private final static Logger logger = LoggerFactory.getLogger(AuthService.class);

    @Autowired
    AuthDao authDao;

    public List userList() {
        return authDao.userList();
    }

    public List roleList() {
        return authDao.roleList();
    }

    public List funcList() {
        return authDao.funcList();
    }

    public List areaList() {
        return authDao.areaList();
    }

    public List rolesForUser(Map param) {
        return authDao.rolesForUser(param);
    }

    public List funcsForRole(Map param) {
        return authDao.funcsForRole(param);
    }

    public int authAdd(Map param) {
        return authDao.authAdd(param);
    }

    /**
     * 为带有area_id的tree添加上area信息
     *
     * @param treeList
     * @param areaList
     * @return
     */
    public List dealAreaTree(List<Map> treeList, List<Map> areaList) {
        List list = new ArrayList();

        Set uaSet = new HashSet();
        for (Map m : treeList) {
            String pId = (String) m.get("pId");
            if (uaSet.contains(pId)) {// 避免重复处理相同数据
                continue;
            }
            uaSet.add(pId);
            getAreaParent(pId, areaList, list);
        }

        return list;
    }

    /**
     * 迭代处理获取area的父节点，直到根节点
     *
     * @param pId
     * @param areaList
     * @param returnList
     */
    private void getAreaParent(String pId, List<Map> areaList, List<Map> returnList) {
        if (null == pId || null == areaList) {
            return;
        }
        for (Map m : areaList) {
            if (pId.equals(m.get("id"))) {
                if (!returnList.contains(m)) {
                    returnList.add(m);
                }
                String curPId = (String) m.get("pId");
                if (null == curPId || curPId.length() == 0) {
                    return;
                } else {
                    getAreaParent(curPId, areaList, returnList);
                }
            }
        }

    }

    @Transactional
    public int authAdd(List<String> userIds, List<String> roleIds, List<String> funcIds) {
        int result = 1;

        try {
            if (userIds.size() > 0 && roleIds.size() > 0 && funcIds.size() > 0) {
                // 保存user和role，role和func，不保存user和func
                authAddRoleUser(roleIds, userIds, false);
                authAddRoleFunc(roleIds, funcIds, false);
            } else if (userIds.size() > 0 && roleIds.size() > 0
                    && funcIds.size() == 0) {
                // 保存user和role
                authAddRoleUser(roleIds, userIds, false);
            } else if (userIds.size() > 0 && roleIds.size() == 0
                    && funcIds.size() > 0) {
                // 保存user和func
                authAddUserFunc(userIds, funcIds);
            } else if (userIds.size() == 0 && roleIds.size() > 0
                    && funcIds.size() > 0) {
                // 保存role和func
                authAddRoleFunc(roleIds, funcIds, false);
            }
        } catch (Exception e) {
            result = 0;
            logger.error(e.toString());
        }

        return result;
    }

    @Transactional
    public int authAddUserFunc(List<String> userIds, List<String> funcIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        Map param = new HashMap();
        param.put("adminId", sessionBean.getUserId());
        param.put("adminName", sessionBean.getUserName());
        param.put("adminTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

        try {
            for (String userId : userIds) {
                for (String funcIdstr : funcIds) {
                    String funcIdArr[] = funcIdstr.split(",");
                    String funcId = funcIdArr[0];
                    String padd = funcIdArr[1];
                    String pmodify = funcIdArr[0];
                    String pdelete = funcIdArr[1];
                    String pupload = funcIdArr[2];
                    String pdownload = funcIdArr[3];
                    param.put("userId", userId);
                    param.put("funcId", funcId);
                    param.put("padd", padd);
                    param.put("pmodify", pmodify);
                    param.put("pdelete", pdelete);
                    param.put("pupload", pupload);
                    param.put("pdownload", pdownload);
                    authDao.authDeleteUserFunc(param);
                    authDao.authAddUserFunc(param);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }

        return 1;
    }

    @Transactional
    public int authAddRoleFunc(List<String> roleIds, List<String> funcIds, Boolean deleteFuncAll) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        Map param = new HashMap();
        param.put("adminId", sessionBean.getUserId());
        param.put("adminName", sessionBean.getUserName());
        param.put("adminTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

        try {
            if(deleteFuncAll){ // 先删除角色的所有功能，根据roleId删除
                for (String roleId : roleIds) {
                    param.put("roleId", roleId);
                    authDao.authDeleteRoleFuncByRoleId(param);
                }
            }

            for (String roleId : roleIds) {
                for (String funcIdstr : funcIds) {
                    String funcIdArr[] = funcIdstr.split(",");
                    String funcId = funcIdArr[0];
                    String padd = funcIdArr[1];
                    String pmodify = funcIdArr[2];
                    String pdelete = funcIdArr[3];
                    String pupload = funcIdArr[4];
                    String pdownload = funcIdArr[5];
                    param.put("roleId", roleId);
                    param.put("funcId", funcId);
                    param.put("padd", padd);
                    param.put("pmodify", pmodify);
                    param.put("pdelete", pdelete);
                    param.put("pupload", pupload);
                    param.put("pdownload", pdownload);
                    if(!deleteFuncAll){ // 防止数据重复，根据roleId和funcId删除
                        authDao.authDeleteRoleFunc(param);
                    }
                    authDao.authAddRoleFunc(param);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }

        return 1;
    }

    @Transactional
    public int authAddRoleUser(List<String> roleIds, List<String> userIds, Boolean deleteRoleAll) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        Map param = new HashMap();
        param.put("adminId", sessionBean.getUserId());
        param.put("adminName", sessionBean.getUserName());
        param.put("adminTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

        try {
            if(deleteRoleAll){ // 先删除用户的所有角色，根据userId删除
                for (String userId : userIds) {
                    param.put("userId", userId);
                    authDao.authDeleteRoleUserByUserId(param);
                }
            }

            for (String userId : userIds) {
                for (String roleId : roleIds) {
                    param.put("userId", userId);
                    param.put("roleId", roleId);
                    if(!deleteRoleAll){ // 防止数据重复，根据roleId和userId删除
                        authDao.authDeleteRoleUser(param);
                    }
                    authDao.authAddRoleUser(param);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }

        return 1;
    }

    @Transactional
    public int authDelete(List<String> userIds, List<String> roleIds, List<String> funcIds) {
        int result = 1;

        try {
            if (userIds.size() > 0 && roleIds.size() > 0 && funcIds.size() > 0) {
                // 删除user和role，role和func，不保存user和func
                authDeleteRoleUser(roleIds, userIds);
                authDeleteRoleFunc(roleIds, funcIds);
            } else if (userIds.size() > 0 && roleIds.size() > 0
                    && funcIds.size() == 0) {
                // 删除user和role
                authDeleteRoleUser(roleIds, userIds);
            } else if (userIds.size() > 0 && roleIds.size() == 0
                    && funcIds.size() > 0) {
                // 删除user和func
                authDeleteUserFunc(userIds, funcIds);
            } else if (userIds.size() == 0 && roleIds.size() > 0
                    && funcIds.size() > 0) {
                // 删除role和func
                authDeleteRoleFunc(roleIds, funcIds);
            }
        } catch (Exception e) {
            result = 0;
            logger.error(e.toString());
        }

        return result;
    }

    @Transactional
    public int authDeleteUserFunc(List<String> userIds, List<String> funcIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        Map param = new HashMap();

        try {
            for (String userId : userIds) {
                for (String funcId : funcIds) {
                    param.put("userId", userId);
                    param.put("funcId", funcId);
                    authDao.authDeleteUserFunc(param);
                    authDao.authDeleteUserFunc(param);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }

        return 1;
    }

    @Transactional
    public int authDeleteRoleFunc(List<String> roleIds, List<String> funcIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        Map param = new HashMap();

        try {
            for (String roleId : roleIds) {
                for (String funcId : funcIds) {
                    param.put("roleId", roleId);
                    param.put("funcId", funcId);
                    authDao.authDeleteRoleFunc(param);
                    authDao.authDeleteRoleFunc(param);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }

        return 1;
    }

    @Transactional
    public int authDeleteRoleUser(List<String> roleIds, List<String> userIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        Map param = new HashMap();

        try {
            for (String userId : userIds) {
                for (String roleId : roleIds) {
                    param.put("userId", userId);
                    param.put("roleId", roleId);
                    authDao.authDeleteRoleUser(param);
                    authDao.authDeleteRoleUser(param);
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
            return 0;
        }

        return 1;
    }

    // 数据权限============================================================================================
    @Transactional
    public int authScopeAdd(List<String> userIds, List<String> areaIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        int result = 1;

        try {
            if (userIds.size() > 0 && areaIds.size() > 0) {
                Map param = new HashMap();
                param.put("adminId", sessionBean.getUserId());
                param.put("adminName", sessionBean.getUserName());
                param.put("adminTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

                for (String userId : userIds) {
                    for (String areaId : areaIds) {
                        param.put("userId", userId);
                        param.put("areaId", areaId);
                        authDao.authScopeDeleteUserArea(param);
                        authDao.authScopeAddUserArea(param);
                    }
                }
            }
        } catch (Exception e) {
            result = 0;
            logger.error(e.toString());
        }

        return result;
    }

    @Transactional
    public int authScopeExcludeAdd(List<String> userIds, List<String> areaIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        int result = 1;

        try {
            if (userIds.size() > 0 && areaIds.size() > 0) {
                Map param = new HashMap();
                param.put("adminId", sessionBean.getUserId());
                param.put("adminName", sessionBean.getUserName());
                param.put("adminTime", DateUtil.getInstance().getToday(InitParam.FORMAT_TIME));

                for (String userId : userIds) {
                    for (String areaId : areaIds) {
                        param.put("userId", userId);
                        param.put("areaId", areaId);
                        authDao.authScopeExcludeDeleteUserArea(param);
                        authDao.authScopeExcludeAddUserArea(param);
                    }
                }
            }
        } catch (Exception e) {
            result = 0;
            logger.error(e.toString());
        }

        return result;
    }

    @Transactional
    public int authScopeDelete(List<String> userIds, List<String> areaIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        int result = 1;

        try {
            if (userIds.size() > 0 && areaIds.size() > 0) {
                Map param = new HashMap();

                for (String userId : userIds) {
                    for (String areaId : areaIds) {
                        param.put("userId", userId);
                        param.put("areaId", areaId);
                        authDao.authScopeDeleteUserArea(param);
                    }
                }
            }
        } catch (Exception e) {
            result = 0;
            logger.error(e.toString());
        }

        return result;
    }

    @Transactional
    public int authScopeExcludeDelete(List<String> userIds, List<String> areaIds) {
        SessionBean sessionBean = (SessionBean) SecurityUtils.getSubject().getPrincipal();

        int result = 1;

        try {
            if (userIds.size() > 0 && areaIds.size() > 0) {
                Map param = new HashMap();

                for (String userId : userIds) {
                    for (String areaId : areaIds) {
                        param.put("userId", userId);
                        param.put("areaId", areaId);
                        authDao.authScopeExcludeDeleteUserArea(param);
                    }
                }
            }
        } catch (Exception e) {
            result = 0;
            logger.error(e.toString());
        }

        return result;
    }


}
